# -*- coding: utf-8 -*-
"""
无依赖系统测试
测试核心逻辑和算法框架，不依赖torch和pandas
"""
import sys
import os
import random
from datetime import datetime
from collections import defaultdict, Counter

class SimplifiedLotteryPredictor:
    """简化的彩票预测器，不依赖复杂库"""
    
    def __init__(self, algorithm_name, lottery_type='ssq'):
        self.algorithm_name = algorithm_name
        self.lottery_type = lottery_type
        self.is_trained = False
        
        # 设置彩票参数
        if lottery_type == 'ssq':
            self.red_range = (1, 33)
            self.blue_range = (1, 16)
            self.red_count = 6
            self.blue_count = 1
        else:  # dlt
            self.red_range = (1, 35)
            self.blue_range = (1, 12)
            self.red_count = 5
            self.blue_count = 2
    
    def train(self, historical_data):
        """训练模型"""
        self.is_trained = True
        print(f"✅ {self.algorithm_name} 训练完成，数据量：{len(historical_data)}期")
        return True
    
    def predict(self, recent_data, num_predictions=1):
        """生成预测"""
        if not self.is_trained:
            print(f"⚠️ {self.algorithm_name} 未训练，使用随机预测")
        
        predictions = []
        for i in range(num_predictions):
            # 生成红球
            red_balls = sorted(random.sample(
                range(self.red_range[0], self.red_range[1] + 1), 
                self.red_count
            ))
            
            # 生成蓝球
            blue_balls = random.sample(
                range(self.blue_range[0], self.blue_range[1] + 1), 
                self.blue_count
            )
            
            predictions.append({
                'red': red_balls,
                'blue': blue_balls,
                'algorithm': self.algorithm_name,
                'confidence': random.uniform(0.3, 0.8)
            })
        
        return predictions

class SimpleConsecutiveTracker:
    """简化的连续模式追踪器"""
    
    def __init__(self, lottery_type='ssq'):
        self.lottery_type = lottery_type
        self.consecutive_patterns = defaultdict(list)
        self.pattern_weights = {}
    
    def analyze_consecutive_patterns(self, historical_data):
        """分析连续模式"""
        patterns_found = 0
        
        # 分析连续2-4期的模式
        for pattern_length in [2, 3, 4]:
            patterns_found += self._find_consecutive_patterns(
                historical_data, pattern_length
            )
        
        # 计算权重
        self._calculate_weights()
        
        return {
            'consecutive_patterns': dict(self.consecutive_patterns),
            'pattern_weights': self.pattern_weights,
            'total_patterns': patterns_found
        }
    
    def _find_consecutive_patterns(self, historical_data, length):
        """查找指定长度的连续模式"""
        patterns_found = 0
        
        for number in range(1, 34):  # 双色球红球范围
            consecutive_count = 0
            
            for period in historical_data:
                # 假设historical_data是期号列表，每期包含7个数字（6红1蓝）
                red_balls = period[:6] if len(period) >= 6 else period
                
                if number in red_balls:
                    consecutive_count += 1
                    if consecutive_count >= length:
                        pattern_key = f"consecutive_{number}_{length}"
                        self.consecutive_patterns[pattern_key].append({
                            'number': number,
                            'length': consecutive_count
                        })
                        patterns_found += 1
                else:
                    consecutive_count = 0
        
        return patterns_found
    
    def _calculate_weights(self):
        """计算模式权重"""
        for pattern_key, patterns in self.consecutive_patterns.items():
            if patterns:
                weight = min(len(patterns) * 0.1, 1.0)
                self.pattern_weights[pattern_key] = weight
    
    def predict_by_patterns(self, recent_data, top_k=5):
        """基于模式预测"""
        predictions = []
        
        # 基于历史模式给出建议
        for pattern_key, weight in sorted(
            self.pattern_weights.items(), 
            key=lambda x: x[1], reverse=True
        )[:top_k]:
            
            # 从模式键中提取数字
            parts = pattern_key.split('_')
            if len(parts) >= 2:
                try:
                    number = int(parts[1])
                    predictions.append((number, weight))
                except ValueError:
                    continue
        
        return predictions

def create_mock_historical_data(num_periods=50):
    """创建模拟历史数据"""
    historical_data = []
    
    for i in range(num_periods):
        # 生成双色球数据：6个红球(1-33) + 1个蓝球(1-16)
        red_balls = sorted(random.sample(range(1, 34), 6))
        blue_ball = random.randint(1, 16)
        
        period_data = red_balls + [blue_ball]
        historical_data.append(period_data)
    
    return historical_data

def create_mock_recent_data(num_periods=5):
    """创建模拟最近数据"""
    recent_data = []
    for i in range(num_periods):
        # 简化的特征数据
        features = [random.uniform(0, 1) for _ in range(7)]
        recent_data.append(features)
    
    return recent_data

def test_simplified_system():
    """测试简化系统"""
    print("🎲 简化多算法系统测试")
    print("=" * 50)
    
    # 创建测试数据
    print("创建模拟数据...")
    historical_data = create_mock_historical_data(100)
    recent_data = create_mock_recent_data(10)
    
    print(f"   历史数据：{len(historical_data)}期")
    print(f"   最近数据：{len(recent_data)}期")
    
    # 测试模式分析
    print("\n🔍 测试模式分析...")
    tracker = SimpleConsecutiveTracker('ssq')
    pattern_results = tracker.analyze_consecutive_patterns(historical_data)
    
    print(f"   发现连续模式：{pattern_results['total_patterns']}个")
    print(f"   模式权重数：{len(pattern_results['pattern_weights'])}")
    
    # 测试预测算法
    print("\n🤖 测试预测算法...")
    algorithms = {
        'LSTM-简化版': SimplifiedLotteryPredictor('LSTM-简化版', 'ssq'),
        '梯度提升-简化版': SimplifiedLotteryPredictor('梯度提升-简化版', 'ssq'),
        '模式记忆-简化版': SimplifiedLotteryPredictor('模式记忆-简化版', 'ssq')
    }
    
    all_predictions = []
    algorithm_results = {}
    
    for name, algorithm in algorithms.items():
        print(f"\n🔧 测试 {name}...")
        start_time = datetime.now()
        
        try:
            # 训练
            algorithm.train(historical_data)
            
            # 预测
            predictions = algorithm.predict(recent_data, num_predictions=3)
            
            end_time = datetime.now()
            duration = (end_time - start_time).total_seconds()
            
            algorithm_results[name] = {
                'status': '✅ 成功',
                'predictions': predictions,
                'duration': duration
            }
            
            all_predictions.extend(predictions)
            
            print(f"   ✅ 成功 | {len(predictions)}组预测 | {duration:.3f}s")
            
            # 显示预测示例
            for i, pred in enumerate(predictions[:2], 1):  # 只显示前2个
                red = pred['red']
                blue = pred['blue']
                confidence = pred['confidence']
                print(f"      预测{i}: 红球{red} 蓝球{blue} 置信度:{confidence:.2f}")
                
        except Exception as e:
            algorithm_results[name] = {
                'status': '❌ 失败',
                'error': str(e)
            }
            print(f"   ❌ 失败: {e}")
    
    # 分析预测多样性
    print(f"\n🎨 预测多样性分析:")
    analyze_prediction_diversity(all_predictions)
    
    # 基于模式的预测
    print(f"\n 基于模式的预测:")
    pattern_predictions = tracker.predict_by_patterns(recent_data)
    if pattern_predictions:
        print("   推荐号码（基于历史模式）:")
        for number, weight in pattern_predictions[:5]:
            print(f"      号码 {number:2d} - 权重 {weight:.2f}")
    else:
        print("   未发现强模式")
    
    # 测试总结
    print(f"\n 测试总结:")
    successful = [name for name, result in algorithm_results.items() 
                 if result['status'] == '✅ 成功']
    
    print(f"   成功算法: {len(successful)}/{len(algorithm_results)}")
    print(f"   总预测数: {len(all_predictions)}")
    
    if len(successful) >= 2:
        print("🎉 简化系统运行正常！")
        print("📝 下一步：安装完整依赖后运行完整版本")
    else:
        print("⚠️ 需要检查算法逻辑")
    
    return algorithm_results

def analyze_prediction_diversity(predictions):
    """分析预测多样性"""
    if not predictions:
        print("   无预测数据")
        return
    
    all_red_numbers = []
    all_blue_numbers = []
    
    for pred in predictions:
        if isinstance(pred, dict):
            all_red_numbers.extend(pred.get('red', []))
            all_blue_numbers.extend(pred.get('blue', []))
    
    if all_red_numbers:
        unique_red = len(set(all_red_numbers))
        total_red = len(all_red_numbers)
        red_diversity = unique_red / total_red if total_red > 0 else 0
        
        print(f"   红球多样性: {unique_red}/{total_red} = {red_diversity:.1%}")
        
        # 频率分析
        red_freq = Counter(all_red_numbers)
        most_common = red_freq.most_common(3)
        print(f"   热门红球: {', '.join([f'{num}({freq}次)' for num, freq in most_common])}")
    
    if all_blue_numbers:
        unique_blue = len(set(all_blue_numbers))
        total_blue = len(all_blue_numbers)
        blue_diversity = unique_blue / total_blue if total_blue > 0 else 0
        
        print(f"   蓝球多样性: {unique_blue}/{total_blue} = {blue_diversity:.1%}")

def main():
    """主函数"""
    print("🎰 LottoProphet 简化系统测试")
    print(f"测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print()
    
    try:
        # 设置随机种子以获得可重复的结果
        random.seed(42)
        
        results = test_simplified_system()
        
        successful_count = len([r for r in results.values() 
                              if r['status'] == '✅ 成功'])
        
        print(f"\n🏁 测试完成!")
        print(f"成功算法: {successful_count}/{len(results)}")
        
        if successful_count >= 2:
            print("🎉 核心逻辑工作正常！")
            print("📦 下一步：pip install torch pandas 安装完整依赖")
        else:
            print("🔧 需要修复算法逻辑")
            
    except Exception as e:
        print(f" 测试过程出错: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()